package com.kla.power.config;

import com.kla.power.util.RedisUtils;
import com.kla.power.util.StateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class ZnpvInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ( HttpMethod.OPTIONS.toString ().equals ( request.getMethod () ) ) {
            response.setStatus ( HttpServletResponse.SC_OK );
            return true;
        }
        String token = request.getHeader ( "Token" );
        if ( token == null || "".equals ( token ) ) {
            response.setHeader ( "Content-type", "application/json;charset=UTF-8" );
            response.setCharacterEncoding ( "UTF-8" );
            PrintWriter out = response.getWriter ();
            out.write ( StateEnum.SESSION_EXPIRE.getCode () );
            out.close ();
            return false;
        }
        Object userEntity = RedisUtils.get ( token );
        if ( userEntity == null ) {
            response.setHeader ( "Content-type", "application/json;charset=UTF-8" );
            response.setCharacterEncoding ( "UTF-8" );
            PrintWriter out = response.getWriter ();
            out.write ( StateEnum.SESSION_EXPIRE.getCode () );
            out.close ();
            return false;
        }
        return true; // 只有返回为true才会回到业务方法执行
    }

    @Override
    public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
